package MTT::Controller::Dictionary;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

use utf8;

use Data::Dumper;
use POSIX qw(strftime);
use Tie::IxHash;

my %tables = (
	trunks => 'trunks',
	masks  => 'masks'
);


tie my %trunk_cols, 'Tie::IxHash', (
	trunk => 'Транк',
	protocol_voip => 'protocol_voip',
	ss7_client => 'ss7_client',	
	ss7_mtt => 'ss7_mtt',
	e1 => 'e1',
	ts => 'ts',
	e1_block => 'e1_block',
	ts_block => 'ts_block',
	type => 'type',
	switch_name => 'Название коммутатора',
	vendor_name => 'vendor_name',
	switch	=> 'Коммутатор',
	subs_name => 'subs_name',
	company_group => 'Группа компаний',
	company_name => 'Компания',
	city => 'Город',
	oblast => 'Регион',
	switch_type => 'Тип коммутатора',
	fo => 'Округ',
	descr => 'descr',
	traffic_type => 'traffic_type',
	created => 'Дата',
);

my @trunks_not_req = (
	[ protocol_voip => 'protocol_voip' ],
	[ ss7_client => 'ss7_client' ],	
	[ ss7_mtt => 'ss7_mtt' ],
	[ e1 => 'e1' ],
	[ ts => 'ts' ],
	[ e1_block => 'e1_block' ],
	[ ts_block => 'ts_block' ],
	[ type => 'type' ],
	[ vendor_name => 'vendor_name' ],
	[ subs_name => 'subs_name' ],
	[ descr => 'descr' ],
	[ traffic_type => 'traffic_type' ]
);

tie my %mask_cols, 'Tie::IxHash', (
	mask 		 => 'Код',
	country_code => 'Код страны',
	code1 		 => 'Код 1',
	code2 		 => 'Код 2',
	fake_mask 	 => 'Принадлежность',
	country 	 => 'Страна',
	area 		 => 'Округ',
	region 		 => 'Регион',
	city 		 => 'Город',
	operator 	 => 'Оператор',
	type  	 	 => 'Тип',
	crc 		 => 'crc32'
);

my %tables_cols = (
	trunks => \%trunk_cols,
	masks  => \%mask_cols
);


sub trunks :Local {
    my ( $self, $c ) = @_;

	if ( $c->req->params->{submit} ) {
		my $sql = $self->get_sql($c);

		my @data;
		my $sth = $c->model('DBIC')->schema()->storage->dbh->prepare($sql);
		$sth->execute();
		while ( my $row = $sth->fetch ) {
			push @data, [ @$row ];
		}

		$c->stash(
			header => $self->get_header('trunks'),
			data   => \@data	
		);
	}

	my @view_fields = $self->get_view_fields('trunks');
	$c->stash(
		template => 'dic_trunks.tt2',
		created	 => strftime('%Y-%m-%d', localtime),
		view_fields => \@view_fields,
		other_fields => \@trunks_not_req 
	);

}

sub masks :Local {
    my ( $self, $c ) = @_;

	if ( $c->req->params->{run} || $c->req->params->{order_by} ) {
		my $sql = $self->get_sql($c);

		my @data;
		my $sth = $c->model('DBIC')->schema()->storage->dbh->prepare($sql);
		$sth->execute();
		while ( my $row = $sth->fetch ) {
			push @data, [ @$row ];
		}

		$c->stash(
			header => $self->get_header('masks'),
			data   => \@data	
		);
	}

	my @view_fields = $self->get_view_fields('trunks');
	$c->stash(
		template => 'dic_masks.tt2',
	);
}

sub get_header {
	my ($self, $table) = @_;

	return unless $table;

	if ( $table eq 'trunks' ) {
		return [ values %trunk_cols ];
	}
	elsif ( $table eq 'masks' ) {
		my @h = map { [ $_ => $mask_cols{$_} ] } keys %mask_cols;
		return \@h; 
	}
}

sub get_field_names {
	my ($self, $table) = @_;

	return keys %{ $tables_cols{ $table } };
}

sub get_view_fields {
	my ($self, $table) = @_;

	my $tc = $tables_cols{ $table };
	return map { [ "view_$_" => $tc->{$_} ] } keys %$tc; 
}

sub get_order_by {
	my ($self, $table, $field) = @_;

	if ( $table eq 'trunks' ) {
		return '';
	}
	elsif ( $table eq 'masks' ) {
		unless ( $field ) {
			return ' ORDER BY country_code, code1, code2';
		}
		else {
			return " ORDER BY $field";
			return '';
		}
	}
}

sub get_sql {
	my ($self, $c, $fields) = @_;

	my %p = %{ $c->req->params };
	
	my $table = delete $p{table};
	return unless $tables{ $table };

	my (@where_fields, @select_fields);
	my $all_fields = $p{all_fields};
	my $select_all;

	if ( my $oval = delete $p{other_field} ) {
		my $oname = delete $p{other_fields};
		push @where_fields, [$oname => $oval];
	}

	delete $p{submit};

	my $created = delete $p{created};
#	$created = strftime('%Y-%m-%d', localtime) unless $created; 

	my @all_fields = $self->get_field_names( $table );

	foreach my $name ( @all_fields ) {
		if ( $p{ "view_$name" } ) {
			push @select_fields, $name;
		}
		else {
			push @where_fields, [ $name => $p{$name} ]
				if $p{ $name };
		}
	}

	@select_fields = @all_fields unless scalar @select_fields;

	my $sql = 'SELECT ' . ( scalar(@select_fields) 
							? join(', ', @select_fields) 
							: '*' ) 
						. " FROM $table WHERE 1=1";
	

	if ( $table eq 'trunks' && $created ) { 
		$sql .= qq{ AND created = '$created' };
	}

	foreach ( @where_fields ) {
		$sql .= " AND $_->[0] LIKE " . qq{'\%$_->[1]\%'}; 
	}

	$sql .= $self->get_order_by( $table, $p{order_by} );

	warn "----- 13 ----->>>\n" . $sql;

	return $sql;
}


=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
